﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace AutomateClient
{
    public partial class MainWindow : Form
    {
        // Private variable
        SerialPort _serialPort = new SerialPort();
        int sequence, totalSequence;

        public MainWindow()
        {
            InitializeComponent();
            // Custom Init
            CustomInitialize();
            sequence = 5;
            totalSequence = sequence + 1;
        }

        private void CustomInitialize()
        {
            string[] comPort = SerialPort.GetPortNames();
            if (comPort.Length > 0)
            {
                for (int i = 0; i < comPort.Length; i++)
                    cmbCom.Items.Add(comPort[i]);
            }
            
        }

        public SerialPort MySerialPort
        {
            get
            {
                return _serialPort;
            }
        }

        private void btnCheckReject_Click(object sender, EventArgs e)
        {
            // Rejet 43
            // Petite moyenne gtrande 40, 41, 42
            // Interroge en lecture le régisgtre N7:0
            string seq = (sequence < 10) ? "0" : "";
            string totalseq = (totalSequence < 10) ? "0" : "";
            string interrogation = "00000F00" + seq + sequence.ToString() + "000100000100" + totalseq +totalSequence.ToString() + "070702";
            
            string bcc = "";
            string affichage = "";
            bcc = CalculeBCC(interrogation);
            if (ConnectToSerial())
                interrogation = string.Format("10061002{0}1003{1}", interrogation, bcc);
            for (int item = 0; item < interrogation.Length / 2; item++)
            {
                affichage += interrogation[item * 2].ToString() + interrogation[(item * 2) + 1].ToString() + " ";
            }
            txtSortie.Text += String.Format("\n\rRequest: \n\r{0}\n\r", affichage);
                // Écrire vers le server
                MySerialPort.DiscardOutBuffer();
            MySerialPort.DiscardInBuffer();
            Byte[] toOut = GetBytesFromString(interrogation);
            //for (int i = 0; i < toOut.Length; i++)
             MySerialPort.Write(toOut, 0, toOut.Length);
             sequence++;
             //totalSequence = sequence + 1;
                // Read port
             
             ReadResponse();
             UnConnectToSerial();
             
        }

        private void ReadResponse()
        {
            Thread.Sleep(2000);
            int valeur;
            string Chaine = "";
            string affichage = "";
            while (MySerialPort.BytesToRead > 0)
            {
                valeur = MySerialPort.ReadChar();
                Chaine += ((valeur < 10) ? "0" : "") + Convert.ToString((char)valeur, 16) + " ";
               // Chaine += (valeur % 16 == 0) ? "0" : "";
            }

            txtSortie.Text += String.Format("\n\rAnswer : \n\r{0}\n\r", affichage);
            txtSortie.Text += String.Format("\n\r{0}\n\r", Chaine);
            txtSortie.ScrollToCaret();
            string[] datadata = Chaine.Split(' ');
            if (datadata.Length > 10)
                txtRejectQty.Text = datadata[10].ToString();
        }

        private Byte[] GetBytesFromString(string streamArray)
        {
            
            int computedValue = 0;
            Byte[] toOut = new Byte[streamArray.Length / 2];

            string[] splittedValue = new string[streamArray.Length / 2];

            for (int i = 0; i < splittedValue.Length; i++)
            {
                splittedValue[i] = streamArray[i * 2].ToString() + streamArray[(i * 2) + 1].ToString();
            }

            for (int i = 0; i < splittedValue.Length; i++)
            {
                computedValue = Convert.ToInt32(splittedValue[i], 16);
                toOut[i] = (Byte)computedValue;
            }

            return toOut;
        }
        private void btnPieceQty_Click(object sender, EventArgs e)
        {
            // Rejet 43
            // Petite moyenne gtrande 40, 41, 42
            // Interroge en lecture le régisgtre N7:0
            string seq = (sequence < 10) ? "0" : "";
            string totalseq = (totalSequence < 10) ? "0" : "";
            string interrogation1 = "00000F00" + seq + sequence.ToString() + "000100000100" + totalseq + totalSequence.ToString() + "070902";
            sequence++;
            seq = (sequence < 10) ? "0" : "";
            totalseq = (totalSequence < 10) ? "0" : "";
            string interrogation2 = "00000F00" + seq + sequence.ToString() + "000100000100" + totalseq + totalSequence.ToString() + "078002";
            sequence++;
            seq = (sequence < 10) ? "0" : "";
            totalseq = (totalSequence < 10) ? "0" : "";
            string interrogation3 = "00000F00" + seq + sequence.ToString() + "000100000100" + totalseq + totalSequence.ToString() + "074302";
            sequence++;

            string bcc = "";
            string affichage = "";
            bcc = CalculeBCC(interrogation1);
            if (ConnectToSerial())
                interrogation1 = string.Format("10061002{0}1003{1}", interrogation1, bcc);
            for (int item = 0; item < interrogation1.Length / 2; item++)
            {
                affichage += interrogation1[item * 2].ToString() + interrogation1[(item * 2) + 1].ToString() + " ";
            }
            txtSortie.Text += String.Format("\n\rRequest: \n\r{0}\n\r", affichage);
            // Écrire vers le server
            MySerialPort.DiscardOutBuffer();
            MySerialPort.DiscardInBuffer();
            Byte[] toOut = GetBytesFromString(interrogation1);
            MySerialPort.Write(toOut, 0, toOut.Length);
            ReadResponseGroseur(txtLittleQty);

            bcc = "";
            affichage = "";
            bcc = CalculeBCC(interrogation2);
            //if (ConnectToSerial())
            interrogation2 = string.Format("10061002{0}1003{1}", interrogation2, bcc);
            for (int item = 0; item < interrogation2.Length / 2; item++)
            {
                affichage += interrogation2[item * 2].ToString() + interrogation2[(item * 2) + 1].ToString() + " ";
            }
            txtSortie.Text += String.Format("\n\rRequest: \n\r{0}\n\r", affichage);
            // Écrire vers le server
            MySerialPort.DiscardOutBuffer();
            MySerialPort.DiscardInBuffer();
            toOut = GetBytesFromString(interrogation2);
            MySerialPort.Write(toOut, 0, toOut.Length);
            ReadResponseGroseur(txtMediumQty);

            bcc = "";
            affichage = "";
            bcc = CalculeBCC(interrogation3);
            //if (ConnectToSerial())
            interrogation3 = string.Format("10061002{0}1003{1}", interrogation3, bcc);
            for (int item = 0; item < interrogation3.Length / 2; item++)
            {
                affichage += interrogation3[item * 2].ToString() + interrogation3[(item * 2) + 1].ToString() + " ";
            }
            txtSortie.Text += String.Format("\n\rRequest: \n\r{0}\n\r", affichage);
            // Écrire vers le server
            MySerialPort.DiscardOutBuffer();
            MySerialPort.DiscardInBuffer();
            toOut = GetBytesFromString(interrogation3);
            MySerialPort.Write(toOut, 0, toOut.Length);
            ReadResponseGroseur(txtGrandQty);

            UnConnectToSerial();
        }

        void ReadResponseGroseur(TextBox textbox)
        {
            Thread.Sleep(2000);
            int valeur;
            string Chaine = "";
            string affichage = "";
            while (MySerialPort.BytesToRead > 0)
            {
                valeur = MySerialPort.ReadChar();
                Chaine += ((valeur < 10) ? "0" : "") + Convert.ToString((char)valeur, 16) + " ";
                // Chaine += (valeur % 16 == 0) ? "0" : "";
            }

            txtSortie.Text += String.Format("\n\rAnswer : \n\r{0}\n\r", affichage);
            txtSortie.Text += String.Format("\n\r{0}\n\r", Chaine);
            txtSortie.ScrollToCaret();

            string[] datadata = Chaine.Split(' ');
            if (datadata.Length > 10)
                textbox.Text = datadata[10].ToString();
        }
        /// <summary>
        /// Connect au port série 
        /// </summary>
        /// <returns></returns>
        private bool ConnectToSerial()
        {
            bool success = true;
            int speed;
            
            if (!MySerialPort.IsOpen)
            {
                //MySerialPort.Open();
                if (cmbCom.SelectedItem != null)
                    MySerialPort.PortName = cmbCom.SelectedItem.ToString();
                else
                {
                    success = false;
                    MessageBox.Show("Pas de COM sélectionné");
                }

                if (success)
                {
                    // Parité
                    if (rbNoParity.Checked)
                        MySerialPort.Parity = System.IO.Ports.Parity.None;
                    if (rbImpair.Checked)
                        MySerialPort.Parity = System.IO.Ports.Parity.Odd;
                    if (rbPair.Checked)
                        MySerialPort.Parity = System.IO.Ports.Parity.Even;

                    // Octet
                    if (rbEightBits.Checked)
                        MySerialPort.DataBits = 8;
                    else
                        MySerialPort.DataBits = 7;

                    // stop bit
                    if (rbSBNone.Checked)
                        MySerialPort.StopBits = System.IO.Ports.StopBits.None;
                    if (rbSBOneBit.Checked)
                        MySerialPort.StopBits = System.IO.Ports.StopBits.One;
                    if (rbSBTwoBits.Checked)
                        MySerialPort.StopBits = System.IO.Ports.StopBits.Two;

                    // Vitesse
                    if (cmbSpeed.SelectedItem != null && Int32.TryParse(cmbSpeed.SelectedItem.ToString(), out speed))
                    {
                        MySerialPort.BaudRate = speed;
                    }
                    else
                    {
                        success = false;
                        MessageBox.Show("Pas de vitesse de sélectionnée ou conversion failed");
                    }
                }
                if (success)
                    MySerialPort.Open();
            }
            else
            {
                success = false;
                MessageBox.Show("Port série déja ouvert");
            }
            return success;
        }

        private bool UnConnectToSerial()
        {
            bool success = true;

            if (MySerialPort.IsOpen)
            {
                MySerialPort.Close();
            }
            else
            {
                MessageBox.Show("Port was already closed");
                success = false;
            }

            return success;
        }

        private string CalculeBCC(string streamArray)
        {
            string bcc = "";
            int computedValue = 0;

            string[] splittedValue = new string[streamArray.Length / 2];

            for (int i = 0; i < splittedValue.Length; i++)
            {
                splittedValue[i] = streamArray[i * 2].ToString() + streamArray[(i * 2) + 1].ToString();
            }

            foreach (string hexValue in splittedValue)
            {
                computedValue += Convert.ToInt32(hexValue, 16);
            }
            int bccInt = 0;
            if (computedValue > 256)
            {
                computedValue = computedValue % 256;
                bccInt = 256 - computedValue;
            }
            else
                bccInt = 256 - computedValue;

            bcc = String.Format("{0:X}", bccInt);
            return bcc;
        }
    }
}
